//
//  FirstViewController.m
//  大整数相加
//
//  Created by 陶建 on 2017/2/6.
//  Copyright © 2017年 taoJ. All rights reserved.
//

#import "FirstViewController.h"

@interface FirstViewController ()
@property (weak, nonatomic) IBOutlet UITextField *text1;
@property (weak, nonatomic) IBOutlet UITextField *text2;
@property (weak, nonatomic) IBOutlet UITextField *textsum;

@end

@implementation FirstViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (IBAction)dengyu:(id)sender {
    NSString *strNum1 = @"输入的值1";
    NSString *strNum2 = @"输入的值2";
    NSInteger l1 = strNum1.length; // strNum1长度
    NSInteger l2 = strNum2.length; // strNum2长度
    NSInteger maxl = l1 > l2 ? l1 : l2; // 最大长度
    
    NSMutableArray *string1Array = [NSMutableArray array]; // 数组用来存储每 strNum1 一位的值
    NSMutableArray *string2Array = [NSMutableArray array]; // 数组用来存储每 strNum2 一位的值
    NSMutableArray *stringSumArray = [NSMutableArray array]; // 数组用来存储 结果 每一位的值
    
    // 截取strNum1每一位的值转换成数组
    for (int i = 0; i < l1; i++) {
        NSString *str = [strNum1 substringWithRange:NSMakeRange(i, 1)];
        [string1Array insertObject:str atIndex:0];
    }
    
    // 截取strNum2每一位的值转换成数组
    for (int i = 0; i < l2; i++) {
        NSString *str = [strNum2 substringWithRange:NSMakeRange(i, 1)];
        [string2Array insertObject:str atIndex:0];
    }
    
    // 用来判断同一位相加是否是大于9, 相当于进位1
    BOOL isdayu10 = false;
    
    // 循环相加每一位的值
    for (int i = 0; i < maxl; i++) {
        NSInteger numI1 = 0;
        NSInteger numI2 = 0;
        if (i < l1) numI1 = [string1Array[i] integerValue];
        if (i < l2) numI2 = [string2Array[i] integerValue];
        // 同一位的值相加 再加上之前 进位(isdayu10: 如果大于9值为1, 否则为0)
        NSInteger sum = numI1 + numI2 + isdayu10;
        isdayu10 = sum >= 10; // (isdayu10: 如果大于9值为1, 否则为0)
        
        NSString *sumString = [NSString stringWithFormat:@"%zd", sum];
        if (!isdayu10) {
            [stringSumArray insertObject:sumString atIndex:0];
            continue;
        }
        NSString *lastString = [sumString substringFromIndex:1];
        [stringSumArray insertObject:lastString atIndex:0];
    }
    // 最后判断一下进位是否大于1 需要把1落下
    if (isdayu10) [stringSumArray insertObject:@"1" atIndex:0];
    // 把数组变成字符串
    NSString *sum = [stringSumArray componentsJoinedByString:@""];
    NSLog(@"%@", sum);
}

@end
